<script setup lang="ts">
import { ref, onMounted } from "vue";
import { message } from "ant-design-vue";
import { AccountBookOutlined } from "@ant-design/icons-vue";
import {
  listDormitoryExpenseBillByPage,
  addDormitoryExpenseBill,
  updateDormitoryExpenseBill,
  deleteDormitoryExpenseBill,
} from "@/api/dormitoryExpenseBill";
import type {
  DormitoryExpenseBill,
  DormitoryExpenseBillQueryRequest,
  DormitoryExpenseBillAddRequest,
  DormitoryExpenseBillUpdateRequest,
} from "@/models/dormitoryExpenseBill";
import dayjs from "dayjs";

// 宿舍水电支出管理相关状态
const bills = ref<DormitoryExpenseBill[]>([]);
const billTotal = ref(0);
const billCurrentPage = ref(1);
const billPageSize = ref(6);
const dormitoryIdSearch = ref("");
const billDataSearch = ref("");
const billLoading = ref(false);

// 账单编辑弹窗
const billModalVisible = ref(false);
const billModalTitle = ref("添加账单");
const editingBill = ref<DormitoryExpenseBillUpdateRequest>({
  billId: 0,
  dormitoryId: 0,
  billDate: "",
  totalExpense: 0,
  waterExpense: 0,
  electricityExpense: 0,
});

// 获取账单列表
const fetchBills = async () => {
  billLoading.value = true;
  try {
    const queryRequest: DormitoryExpenseBillQueryRequest = {
      current: billCurrentPage.value,
      pageSize: billPageSize.value,
      dormitoryId: dormitoryIdSearch.value
        ? parseInt(dormitoryIdSearch.value)
        : undefined,
    };
    console.log("billDataSearch: ", billDataSearch.value);
    console.log("billDate", queryRequest.billDate);
    const res = await listDormitoryExpenseBillByPage(queryRequest);
    if (res.data.code === 0) {
      bills.value = res.data.data.records;
      billTotal.value = res.data.data.total;
    } else {
      message.error("获取账单列表失败");
    }
  } catch (error) {
    message.error("获取账单列表失败");
  } finally {
    billLoading.value = false;
  }
};

// 搜索账单
const onSearch = () => {
  billCurrentPage.value = 1;
  fetchBills();
};

// 重置搜索
const handleReset = () => {
  dormitoryIdSearch.value = "";
  billCurrentPage.value = 1;
  fetchBills();
};

// 处理分页变化
const handleTableChange = (pagination: any) => {
  billCurrentPage.value = pagination.current;
  billPageSize.value = pagination.pageSize;
  fetchBills();
};

// 添加账单
const handleAddBill = () => {
  billModalTitle.value = "添加账单";
  editingBill.value = {
    billId: 0,
    dormitoryId: 0,
    billDate: "",
    totalExpense: 0,
    waterExpense: 0,
    electricityExpense: 0,
  };
  billModalVisible.value = true;
};

// 编辑账单
const handleEditBill = (record: DormitoryExpenseBill) => {
  billModalTitle.value = "编辑账单";
  editingBill.value = {
    ...record,
    billDate: dayjs(record.billDate),
  };
  billModalVisible.value = true;
};

// 保存账单
const handleSaveBill = async () => {
  try {
    if (editingBill.value.dormitoryId === 0 || !editingBill.value.billDate) {
      message.error("请填写完整信息");
      return;
    }

    const submitData = {
      ...editingBill.value,
      billDate: editingBill.value.billDate.format("YYYY-MM-DD"),
    };

    if (editingBill.value.billId === 0) {
      // 添加账单
      const res = await addDormitoryExpenseBill(submitData);
      if (res.data.code === 0) {
        message.success("添加成功");
      } else {
        message.error(res.data.message || "添加失败");
      }
    } else {
      // 更新账单
      const res = await updateDormitoryExpenseBill(submitData);
      if (res.data.code === 0) {
        message.success("更新成功");
      } else {
        message.error(res.data.message || "更新失败");
      }
    }
    billModalVisible.value = false;
    fetchBills();
  } catch (error) {
    message.error("操作失败");
  }
};

// 删除账单
const handleDeleteBill = async (record: DormitoryExpenseBill) => {
  try {
    const res = await deleteDormitoryExpenseBill(record.billId);
    if (res.data.code === 0) {
      message.success("删除成功");
      fetchBills();
    } else {
      message.error(res.data.message || "删除失败");
    }
  } catch (error) {
    message.error("删除失败");
  }
};

onMounted(() => {
  fetchBills();
});
</script>

<template>
  <a-card class="info-card">
    <template #title>
      <div class="card-title">
        <account-book-outlined />
        <span>宿舍水电支出管理</span>
      </div>
    </template>
    <template #extra>
      <a-space>
        <a-input
          v-model:value="dormitoryIdSearch"
          placeholder="宿舍ID"
          style="width: 150px"
          @pressEnter="onSearch"
        />
        <a-button type="primary" @click="onSearch">搜索</a-button>
        <a-button @click="handleReset">重置</a-button>
        <a-button type="primary" @click="handleAddBill"> 添加账单 </a-button>
      </a-space>
    </template>

    <a-table
      :dataSource="bills"
      :loading="billLoading"
      :pagination="{
        total: billTotal,
        current: billCurrentPage,
        pageSize: billPageSize,
        showSizeChanger: true,
        showQuickJumper: true,
      }"
      @change="handleTableChange"
    >
      <a-table-column key="billId" title="账单ID" data-index="billId" />
      <a-table-column
        key="dormitoryId"
        title="宿舍ID"
        data-index="dormitoryId"
      />
      <a-table-column
        key="billDate"
        title="账单日期"
        data-index="billDate"
        :customRender="({ text }) => dayjs(text).format('YYYY-MM-DD')"
      />
      <a-table-column
        key="totalExpense"
        title="总支出"
        data-index="totalExpense"
        :customRender="({ text }) => `￥${text.toFixed(2)}`"
      />
      <a-table-column
        key="waterExpense"
        title="水费"
        data-index="waterExpense"
        :customRender="({ text }) => `￥${text.toFixed(2)}`"
      />
      <a-table-column
        key="electricityExpense"
        title="电费"
        data-index="electricityExpense"
        :customRender="({ text }) => `￥${text.toFixed(2)}`"
      />
      <a-table-column
        key="createTime"
        title="创建时间"
        data-index="createTime"
        :customRender="({ text }) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')"
      />
      <a-table-column key="action" title="操作">
        <template #default="{ record }">
          <div>
            <a-button type="link" @click="handleEditBill(record)"
              >编辑</a-button
            >
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除这条账单吗？"
              @confirm="handleDeleteBill(record)"
            >
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
          </div>
        </template>
      </a-table-column>
    </a-table>

    <!-- 账单编辑弹窗 -->
    <a-modal
      v-model:visible="billModalVisible"
      :title="billModalTitle"
      @ok="handleSaveBill"
    >
      <a-form :model="editingBill" layout="vertical">
        <a-form-item label="宿舍ID" required>
          <a-input-number
            v-model:value="editingBill.dormitoryId"
            style="width: 100%"
            :min="1"
          />
        </a-form-item>
        <a-form-item label="账单日期" required>
          <a-date-picker
            v-model:value="editingBill.billDate"
            style="width: 100%"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
          />
        </a-form-item>
        <a-form-item label="水费" required>
          <a-input-number
            v-model:value="editingBill.waterExpense"
            style="width: 100%"
            :min="0"
            :step="0.01"
            prefix="￥"
          />
        </a-form-item>
        <a-form-item label="电费" required>
          <a-input-number
            v-model:value="editingBill.electricityExpense"
            style="width: 100%"
            :min="0"
            :step="0.01"
            prefix="￥"
          />
        </a-form-item>
        <a-form-item label="总支出" required>
          <a-input-number
            v-model:value="editingBill.totalExpense"
            style="width: 100%"
            :min="0"
            :step="0.01"
            prefix="￥"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<style scoped>
.info-card {
  margin-bottom: 24px;
}

.card-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  color: #1f1f1f;
}

.card-title .anticon {
  margin-right: 12px;
  font-size: 20px;
  color: #1890ff;
}
</style>
